package com.antd.auth.handler;

import com.antd.common.auth.exception.ValidateCodeException;
import com.antd.common.auth.util.AntdSecurityUtil;
import com.antd.common.core.util.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO
 *
 * @author 冷言丶冷语
 * @version 1.0
 * @date 2020/9/9 11:25
 */
@Component
public class AntdAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        String message="";
        if(e instanceof BadCredentialsException){
            message = "账号或密码错误";
        }else if(e instanceof DisabledException){
            message = "账号已被禁用";
        }else if(e instanceof LockedException){
            message = "账号已被锁定";
        }else if(e instanceof ValidateCodeException) {
            message = e.getMessage();
        }else if(e instanceof UsernameNotFoundException){
            message = e.getMessage();
        }else{
            message = "认证失败，请联系网站管理员";
        }
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        AntdSecurityUtil.writeJavaScript(R.error(message), response);
    }
}
